package com.smartplatform.security.handlers;

import com.smartplatform.event.LoginEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 咕唧
 * @Date 2022/6/7 10:09
 * @Version 1.0
 */
@Component
public class MyUrlAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        super.onAuthenticationFailure(request, response, exception);
        //这个的返回值就是spring里面的user,也就是我们userdetailservice中的返回值
        Object username = request.getAttribute("username");
        //登陆失败发送事件
        context.publishEvent(new LoginEvent(LoginEvent.LoginType.FAIL, (String) username));
    }
}
